package com.hdw.common.util;

import com.hdw.common.base.BaseException;
import org.nfunk.jep.JEP;
import org.nfunk.jep.Node;
import org.nfunk.jep.ParseException;

import java.util.*;

public class JepUtil {

    public static Object calculate(String expression, Map param ) throws BaseException {
        JEP jep = new JEP();
        Set<Map.Entry> set = param.entrySet();
        for (Map.Entry entry : set) {
            Object entryValue = entry.getValue();
            String entryKey = (String) entry.getKey();
            jep.addVariable(entryKey, entryValue);
        }
        Object result = null;
        try { //执行
            Node parse = jep.parse(expression);
            result = jep.evaluate(parse);
        } catch (ParseException e) {
            throw new BaseException("公式表达式解析失败",e);
        }
        return result;
    }

    public static void main(String argus[]) {
        List<Map> mapList = new ArrayList<>();
        Map map = new HashMap() {{
            put("sum", 4);
            put("b", 0);
            put("c", 3);
        }};
        try {
            Object result = JepUtil.calculate("a+b+c",map);
            System.out.println(result);
        } catch (BaseException e) {
            e.printStackTrace();
        }
    }
}
